<template>
	<div class="yuan-container container">
		<a-card title="生产跟进表">
		
		<a-tabs type="card" @change="tabChange">
			
			<a-tab-pane v-for="(item) in tabsData" :key="item" :tab="item">
			
			<div class="filter-panel">
				<span v-if="item === '饮片-提取-制剂车间'">
					<span style="margin-right: 5px;">品名：</span>
					<a-input
					allowClear
					v-model="productName"
					placeholder="请输入品名或批号"
					style="width: 200px; margin-right: 30px;"
					@pressEnter="onSearch"
					/>
					<span style="margin-right: 5px;">填报状态：</span>
                    <a-select
                        allowClear
                        v-model="tempState"
                        placeholder="请选择填报状态"
                        style="width: 200px; margin-right: 30px;"
                        @pressEnter="onSearch"
                        >
                        <a-select-option value="1">暂存数据</a-select-option>
                        <a-select-option value="2">保存数据</a-select-option>
                    </a-select>
				</span>
				<!-- <span style="margin-right: 5px;">选择标准类型：</span>
				<a-select
				v-model="searchStandard"
				placeholder="标准类型"
				style="width: 120px; margin-right: 10px;"
				@change="onSearch"
				allow-clear
				>
				<a-select-option value="国标">国标</a-select-option>
				<a-select-option value="省标">省标</a-select-option>
				<a-select-option value="省标-北京">省标-北京</a-select-option>
				<a-select-option value="省标-上海">省标-上海</a-select-option>
				</a-select>
				<span style="margin-right: 5px;">选择日期范围：</span>
				<a-range-picker
				v-model="searchDateRange"
				valueFormat="YYYY-MM-DD"
				style="margin-right: 15px;"
				@change="onSearch"
				:locale="locale"
				/> -->
				<a-button v-if="item === '饮片-提取-制剂车间'" type="primary" @click="onSearch">搜索</a-button>
				<div class="filter-list" style="float: right;margin-right: 0">
				<a-button v-if="item === '生产管理室'" style="margin-right:5px" type="primary" @click="add">新增</a-button>
				<a-button style="margin-right:5px" @click="downloadTemplate">下载模板</a-button>
				<a-upload
					:show-upload-list="false"
					:before-upload="beforeUpload"
					accept=".xlsx,.xls"
					style="display: inline-block; margin-right: 5px;"
				>
					<a-button>导入数据</a-button>
				</a-upload>
				<a-button type="primary" style="margin-right:10px" @click="exportData">导出</a-button>
				<a-button type="primary" style="margin-right:0px" @click="exportAllFollowTable">导出总表</a-button>
				</div>
			</div>
			<a-table
				:row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
				:scroll="{ x:  1500 }"
				:loading="tableOption.loading"
				bordered
				:rowKey="item=>item.id"
				:data-source="tableOption.dataSource"
				:columns="tableOption.tableColumns"
				:pagination="tableOption.pagination"
			/>
			</a-tab-pane>
		</a-tabs>
		</a-card>

		<!-- 新增/编辑弹窗 -->
		<AddOrEdit
		:visible.sync="addOrEditVisible"
		:viewDetail="editView"
		:editData="editData"
		:tabName="curTab"
		@success="onAddOrEditSuccess"
		@update:visible="getTableData"
		/>
	</div>
	</template>

<script lang="ts">
	import { Vue, Component, Watch } from 'vue-property-decorator'
	import { h, ref } from "vue"
	import locale from "ant-design-vue/lib/date-picker/locale/zh_CN"
	import { UserModule } from "@/store/modules/userModules"
	import AddOrEdit from './components/addOrEdit.vue'
	import nextApi from '@/api/nextApi'
	import { downLoadFile } from '@/utils'


	// 导出参数接口
interface ExportParams {
	name?: string
	batch?: number
	type: string
}

@Component({
	name: 'ProductionProgress',
	components: {
		AddOrEdit
	}
})
export default class ProductionProgress extends Vue {
	locale = locale
	productName: string = ''
	tempState: string | number = ''
	searchStandard: undefined | string = ''
	searchDateRange: string[] = []
	tabsData: string[] = ['生产管理室', '饮片-提取-制剂车间', '技术部', '物控部','质管部QA']
	curTab: string = '生产管理室'
	selectedRowKeys: any[] = []
    selectedRows:any[] =[]
	// 新增/编辑弹窗相关
	addOrEditVisible: boolean = false
	editData: any = {}

	// 表格配置
	tableOption: any = {
		loading: false,
		tableColumns: [],
		dataSource: [],
		pagination: {
		pageSize: 10,
		current: 1,
		total: 0,
		showTotal: (total: number) => `共${total}条`,
		onChange: this.pageChange,
		}
	}

	mounted() {
		this.tabChange(this.tabsData[0])
	}
	// 监听toggleCollapsed
	@Watch("state")
	stateChange(n: any) {
		if (n) {
		this.tableOption.width = 1760
		} else {
		this.tableOption.width = 1640
		}
	}

	// 获取vuex中的toggleCollapsed
	get state() {
		return UserModule.toggleCollapsed
	}

	//勾选框变化
	onSelectChange(selectedRowKeys: any[], selectedRows: any[]) {
		this.selectedRowKeys = selectedRowKeys
		this.selectedRows = selectedRows
		console.log(this.selectedRows);
		
	}
	async getTableData() {
		try {
			this.tableOption.loading = true
			// 构建查询参数
			const params:any = {
				page: this.tableOption.pagination.current,
				pageSize: this.tableOption.pagination.pageSize,
				name: this.productName,
				tempState: this.tempState,
				tableType: this.curTab
			}
			
			// 调用API
			const response = await nextApi.productionTableDataSelect(params)
			
			if (response && response.data) {
				this.tableOption.dataSource = response.data.records
				this.tableOption.pagination.total = response.data.total
				// 生产管理室返回字段已调整，无需转换额外字段
			} else {
				this.tableOption.dataSource = []
				this.tableOption.pagination.total = 0
			}
			console.log(this.tableOption.dataSource);
			
		} catch (error) {
			console.error('获取数据失败:', error)
			this.$message.error('获取数据失败')
			this.tableOption.dataSource = []
			this.tableOption.pagination.total = 0
			// 保持空数据
		} finally {
			this.tableOption.loading = false
		}
	}



	pageChange(page: number, pageSize: number) {
		this.tableOption.pagination.current = page
		this.getTableData()
	}

	/**
	 * @description tab切换
	 **/
	tabChange(e: string) {
		this.curTab = e
		this.changeColumn()
		this.getTableData()
	}
	changeColumn() {
		switch (this.curTab) {
		case '生产管理室':
				this.tableOption.tableColumns = [
					{ title: '登记日期', dataIndex: 'registrationDate', key: 'registrationDate', align: 'center', width: 120 },
					{ title: '品名', dataIndex: 'name', key: 'name', align: 'center', width: 160 },
					{ title: '品种类型', dataIndex: 'varietyType', key: 'varietyType', align: 'center', width: 120 },
					{ title: '类别', dataIndex: 'type', key: 'type', align: 'center', width: 100 },
					{ title: '成品库存天数（登记时）', dataIndex: 'packDayNumReg', key: 'packDayNumReg', align: 'center', width: 180 },
					{ title: '未扣库存前成品库存天数', dataIndex: 'packDaySubNum', key: 'packDaySubNum', align: 'center', width: 200 },
					{ title: '成品天数（O列）', dataIndex: 'packDayNum', key: 'packDayNum', align: 'center', width: 140 },
					{ title: '成品发货后天数（R列）', dataIndex: 'packDayShipNum', key: 'packDayShipNum', align: 'center', width: 160 },
					{ title: '最新生产状态', dataIndex: 'prodState', key: 'prodState', align: 'center', width: 140 },
					{ title: '生产类型', dataIndex: 'prodType', key: 'prodType', align: 'center', width: 120 },
					{ title: '提取车间', dataIndex: 'extractWorkshop', key: 'extractWorkshop', align: 'center', width: 120 },
					{ title: '药材批号', dataIndex: 'ycBatch', key: 'ycBatch', align: 'center', width: 140 },
					{ title: '药材合格日期', dataIndex: 'ycQualityDate', key: 'ycQualityDate', align: 'center', width: 140 },
					{ title: '计划交货时间', dataIndex: 'deliveryDate', key: 'deliveryDate', align: 'center', width: 160 },
					{ title: '操作', key: 'action', align: 'center', width: 80, fixed: 'right', customRender: (text: string, record: any) => { 
						return h('a', {
							style: { color: '#1890ff', cursor: 'pointer' }, 
							on: { 
								click: () => this.handleEdit(record) 
							}
							}, '编辑') } 
						},
				]
				break
		case '饮片-提取-制剂车间':
			this.tableOption.tableColumns = [
				{ title: '品名', dataIndex: 'name', key: 'name', align: 'center', width: 140 },
				{ title: '药材领用时间', dataIndex: 'ycTakeDate', key: 'ycTakeDate', align: 'center', width: 140 },
				{ title: '提取物批号', dataIndex: 'tqwBatch', key: 'tqwBatch', align: 'center', width: 150 },
				{ title: '来料饮片批号', dataIndex: 'rawYpBatch', key: 'rawYpBatch', align: 'center', width: 160,
					customRender: (text: any, record: any) => {
						const v = record.rawYpBatch
						try {
							if (Array.isArray(v)) {
								const arr = v.map((it: any) => typeof it === 'string' ? it : (it && it.batch) || '').filter((s: string) => !!s)
								return arr.join(', ')
							}
							if (typeof v === 'string') {
								const s = v.trim()
								if (!s) return ''
								if (s.startsWith('[')) {
									const arr = JSON.parse(s)
									const out = Array.isArray(arr) ? arr.map((it: any) => typeof it === 'string' ? it : (it && it.batch) || '').filter((x: string) => !!x) : []
									return out.join(', ')
								}
								return s.split(',').map(x => x.trim()).filter(x => !!x).join(', ')
							}
						} catch(e) {}
						return ''
					}
					 },
				{ title: '提取生产开始时间', dataIndex: 'tqStartTime', key: 'tqStartTime', align: 'center', width: 160 },
                { title: '过筛结束时间', dataIndex: 'gsEndTime', key: 'gsEndTime', align: 'center', width: 140 },
				{ title: '混一送样时间', dataIndex: 'hySampleTime', key: 'hySampleTime', align: 'center', width: 160 },
				{ title: '送检批号（小样）', dataIndex: 'sampleBatchSmall', key: 'sampleBatchSmall', align: 'center', width: 160 },
				{ title: '记录送审日期', dataIndex: 'sampleDate', key: 'sampleDate', align: 'center', width: 160 },
				{ title: 'PC物料方案发放时间', dataIndex: 'pcDistributeDate', key: 'pcDistributeDate', align: 'center', width: 180 },
				{ title: 'PC方案去向', dataIndex: 'pcPlanDirection', key: 'pcPlanDirection', align: 'center', width: 140 },
				{ title: '提取接收方案时间', dataIndex: 'tqReceivingPlanTime', key: 'tqReceivingPlanTime', align: 'center', width: 160 },
				{ title: '粉碎完成时间', dataIndex: 'crushingCompletionTime', key: 'crushingCompletionTime', align: 'center', width: 180 },
				{ title: '制剂接收方案时间', dataIndex: 'zjReceivingPlanTime', key: 'zjReceivingPlanTime', align: 'center', width: 160 },
				{ title: '制粒完成时间', dataIndex: 'zlFinishTime', key: 'zlFinishTime', align: 'center', width: 160 },
				{ title: '颗粒批号', dataIndex: 'klBatch', key: 'klBatch', align: 'center', width: 140 },
				{ title: '是否FS半成品', dataIndex: 'fsFlag', key: 'fsFlag', align: 'center', width: 140 },
				{ title: '未制粒原因', dataIndex: 'notZlReason', key: 'notZlReason', align: 'center', width: 140 },
				{ title: '计划包装时间', dataIndex: 'planPackTime', key: 'planPackTime', align: 'center', width: 160 },
				{ title: '包装完成时间', dataIndex: 'packFinishTime', key: 'packFinishTime', align: 'center', width: 160 },
				{ title: '成品批号', dataIndex: 'prodBatch', key: 'prodBatch', align: 'center', width: 140 },
				{ title: '送检批号（N）', dataIndex: 'sampleBatchN', key: 'sampleBatchN', align: 'center', width: 160 },
				{ title: '未包装原因', dataIndex: 'notPackReason', key: 'notPackReason', align: 'center', width: 140 },
				{ title: '填报状态', dataIndex: 'tempState', key: 'tempState', align: 'center', width: 100 },
				{ title: '操作', key: 'action', align: 'center', width: 100, fixed: 'right', customRender: (text: string, record: any) => { 
					const s = record.tempState; 
					const label = s === '1' ? '继续填写' : s === '2' ? '详情' : '编辑'; 
					return h('a', { 
						style: { color: '#1890ff', cursor: 'pointer' },
						on: { click: () => this.handleEdit(record) } }, label) } },
			]
			break
        case '技术部':
            this.tableOption.tableColumns = [
                { title: '送检批号（小样）', dataIndex: 'sampleBatchSmall', key: 'sampleBatchSmall', align: 'center', width: 160 },
                { title: '提取物收样时间（技术部填写）', dataIndex: 'tqwSampleTime', key: 'tqwSampleTime', align: 'center' },
                { title: '检验部门（技术部填写）', dataIndex: 'checkDepart', key: 'checkDepart', align: 'center' },
                { title: '提取物检验结果出具时间', dataIndex: 'tqwCheckResultTime', key: 'tqwCheckResultTime', align: 'center', width: 200 },
                { title: '技术部制剂方案发放时间', dataIndex: 'zjPlanDistributeTime', key: 'zjPlanDistributeTime', align: 'center', width: 220 },
                { title: '方案去向', dataIndex: 'planDirection', key: 'planDirection', align: 'center', width: 140 },
                { title: '是否需备案', dataIndex: 'recordFlag', key: 'recordFlag', align: 'center' },
                { title: '操作', key: 'action', align: 'center', width: 80, fixed: 'right', customRender: (text: string, record: any) => { 
                    return h('a', {
                        style: { color: '#1890ff', cursor: 'pointer' }, 
                        on: { click: () => this.handleEdit(record) } 
                        }, '编辑') } },
            ]
            break
        case '物控部':
            this.tableOption.tableColumns = [
                { title: '颗粒批号', dataIndex: 'klBatch', key: 'klBatch', align: 'center' },
                { title: '颗粒送FS时间', dataIndex: 'klFsTime', key: 'klFsTime', align: 'center' },
                { title: '颗粒FS回厂时间', dataIndex: 'klFsBackTime', key: 'klFsBackTime', align: 'center' },
                { title: '成品批号', dataIndex: 'prodBatch', key: 'prodBatch', align: 'center' },
                { title: '成品送FS时间', dataIndex: 'prodFsTime', key: 'prodFsTime', align: 'center' },
                { title: '成品FS回通知送样时间', dataIndex: 'prodFsNoticeTime', key: 'prodFsNoticeTime', align: 'center' },
                { title: '物控部成品移交成品库时间', dataIndex: 'prodTurnTime', key: 'prodTurnTime', align: 'center' },
                { title: '操作', key: 'action', align: 'center', width: 80, fixed: 'right', customRender: (text: string, record: any) => { 
                    return h('a', { 
                        style: { color: '#1890ff', cursor: 'pointer' }, 
                        on: { click: () => this.handleEdit(record) }
                    }, '编辑') } },
            ]
            break
        case '质管部QA':
        this.tableOption.tableColumns = [
            { title: '颗粒批号', dataIndex: 'granuleBatchNo', key: 'granuleBatchNo', align: 'center' },
            { title: '颗粒放行日期', dataIndex: 'klReleaseTime', key: 'klReleaseTime', align: 'center' },
            { title: '未放行原因', dataIndex: 'klNotReleaseReason', key: 'klNotReleaseReason', align: 'center' },
            { title: '颗粒状态', key: 'granuleStatus', align: 'center', customRender: (t:any, r:any)=>{ const a=r.klReleaseTime, b=r.klNotReleaseReason; return (!a && !b) ? '待处理' : (a && !b) ? '已放行' : (!a && b) ? '未放行' : '待处理' } },
            { title: '成品批号', dataIndex: 'finishedBatchNo', key: 'finishedBatchNo', align: 'center' },
            { title: '成品放行时间', dataIndex: 'prodReleaseTime', key: 'prodReleaseTime', align: 'center' },
            { title: '未放行原因', dataIndex: 'prodNotReleaseReason', key: 'prodNotReleaseReason', align: 'center' },
            { title: '成品状态', key: 'finishedStatus', align: 'center', customRender: (t:any, r:any)=>{ const a=r.prodReleaseTime, b=r.prodNotReleaseReason; return (!a && !b) ? '待处理' : (a && !b) ? '已放行' : (!a && b) ? '未放行' : '待处理' } },
            { title: '操作', key: 'action', align: 'center',  customRender: (text: string, record: any) => {
                return h('a', { 
                    style: { color: '#1890ff', cursor: 'pointer' }, 
                    on: { click: () => this.handleEdit(record) } 
                }, '编辑') } },
        ]
            break
		}
	}



	onSearch() {
		this.tableOption.pagination.current = 1
		this.getTableData()
	}

	exportData() {
		nextApi.exportTableByType({tableType:this.curTab}, (response:any) => {
			const blob = new Blob([response.data],{
				type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
			})
			downLoadFile(blob,`生产跟进表_${this.curTab}_${new Date().toISOString().slice(0, 10)}.xlsx`)
		})
	}
	async exportAllFollowTable() {
		try {
			this.$message.loading('正在导出数据...', 0)
			// 调用导出API
			await nextApi.prodFollowExportAllTable({}, (response:any) => {
				const blob = new Blob([response.data],{
					type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
				})
				downLoadFile(blob,`生产跟进总表_${this.curTab}_${new Date().toISOString().slice(0, 10)}.xlsx`)
				this.$message.destroy()
				this.$message.success('导出成功')
			})
		} catch (error) {
			this.$message.destroy()
			console.error('导出失败:', error)
			this.$message.error('导出失败，请重试')
		}
	}

	add() {
			this.editData = {}
			this.addOrEditVisible = true
			this.editView = false
	}
	editView = false
	handleEdit(record: any) {
			this.editData = record
			this.addOrEditVisible = true
			this.editView = true
	}



	// 下载模板
    async downloadTemplate() {
        try {
            this.$message.loading('正在下载模板...', 0)
            // 调用生产跟进表下载模板API
			let params = {
				tableType: this.curTab,
				idList:this.selectedRows,
				name:this.productName,
				tempState:this.tempState,
			}
            await nextApi.prodFollowDownTemplate(params, (response: any) => {
                const blob = new Blob([response.data], {
                    type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                })
                downLoadFile(blob, `生产跟进表模板_${this.curTab}_${new Date().toISOString().slice(0, 10)}.xlsx`)
                this.$message.destroy()
                this.$message.success('模板下载成功')
            })
        } catch (error) {
            this.$message.destroy()
			console.error('下载模板失败:', error)
			this.$message.error('下载模板失败，请重试')
		}
	}

	// 导入数据前的处理
	beforeUpload(file: File) {
		const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
						file.type === 'application/vnd.ms-excel'
		if (!isExcel) {
			this.$message.error('只能上传Excel文件！')
			return false
		}
		const isLt10M = file.size / 1024 / 1024 < 10
		if (!isLt10M) {
			this.$message.error('文件大小不能超过10MB！')
			return false
		}
		this.importData(file)
		return false // 阻止自动上传
	}

	// 导入数据
	async importData(file: File) {
		try {
			this.$message.loading('正在导入数据...', 0)
			
			const formData = new FormData()
			formData.append('file', file)
			formData.append('type', this.curTab)
			
			const response = await nextApi.importTableByType(formData, (response: any) => {
				this.$message.destroy()
				if (response && response.code === 200) {
					this.$message.success('数据导入成功')
					this.getTableData() // 刷新表格数据
				} else {
					this.$message.error(response?.message || '导入失败')
				}
			})
			
			
		} catch (error) {
			this.$message.destroy()
			console.error('导入数据失败:', error)
			this.$message.error('导入数据失败，请重试')
		}
	}

	// 新增/编辑成功回调
	onAddOrEditSuccess() {
		this.getTableData()
	}
}
</script>

	<style lang="scss" scoped>
	.yuan-container {
	.filter-panel {
		padding: 0px;
		.filter-list {
		margin-top: 10px;
		}
	}

	.ant-tabs-card > .ant-tabs-nav .ant-tabs-tab {
		background: #fafafa;
		border-color: #d9d9d9;
		
		&.ant-tabs-tab-active {
		background: #fff;
		border-bottom-color: #fff;
		}
	}

	.ant-table {
		.ant-table-thead > tr > th {
		background-color: #fafafa;
		font-weight: 600;
		}
	}
	}

	// 响应式设计
	@media (max-width: 768px) {
	.yuan-container {
		padding: 10px;

		.filter-panel {
		.filter-list {
			float: none !important;
			margin-top: 15px;
			text-align: center;
		}
		}
	}
	}
	</style>
